<template>
  <div class="chart-container">
    <div
      ref="chartRef"
      :style="{ width: chartWidth, height: chartHeight }"
    ></div>
  </div>
</template>

<script setup>
import { getcart } from "../utils/cart";
import * as echarts from "echarts";
import { ref, onMounted, onBeforeUnmount, inject, computed } from "vue";
import { useStore } from "vuex";
const store=useStore()
// const cartlist = inject("cartlist");
const cartlist = computed(()=>store.getters.getCarList)

// 定义饼图数据
let chartData = [];

// 定义图表尺寸
const chartWidth = "600px";
const chartHeight = "600px";

// 初始化图表
const chartRef = ref(null);
let chartInstance;

const initChart = () => {
  getcart({ status: "未提交", createBy: store.getters.getUser.username }).then(
    (response) => {
      if (response.code == 401) {
        //认证失败，无法访问系统资源,跳转到登录页面
        router.push({ path: "/login" });
        return;
      }
      cartlist.value.splice(0, cartlist.value.length);
      for (let index in response.rows) {
        let newgood = {
          id: response.rows[index],
          img: "/a1.jpg",
          title: "测试",
          describe: "新产品",
          price: 121,
          num: 3,
          memo: "无",
        };
        response.rows[index].img = response.rows[index].img;
        newgood.id = response.rows[index].id;
        newgood.img = response.rows[index].img;
        newgood.title = response.rows[index].title;
        newgood.describe = response.rows[index].mydescribe;
        newgood.price = response.rows[index].price;
        newgood.num = response.rows[index].num;
        newgood.memo = response.rows[index].memo;
        cartlist.value.push(newgood);
      }
    }
  );
  if (cartlist.value.length) {
    cartlist.value.forEach((cart) => {
      chartData.push({ value: cart.num, name: cart.title+"  单价："+cart.price });
    });
    if (!chartInstance) {
      chartInstance = echarts.init(chartRef.value);

      const option = {
        title: {
          text: "购物车统计",
          left: "center", // 将标题居中
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: "left",
          data: chartData.map((item) => item.name),
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["pie", "funnel"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        series: [
          {
            name: "购物车",
            type: "pie",
            radius: "75%",
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };

      chartInstance.setOption(option);

      // 窗口大小改变时更新图表
      window.addEventListener("resize", updateChart);
    }
  }
};

// 更新图表
const updateChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 在组件挂载后初始化图表
onMounted(() => {
  initChart();
});

// 在组件卸载前清除图表实例
onBeforeUnmount(() => {
  if (chartInstance) {
    window.removeEventListener("resize", updateChart);
    chartInstance.dispose();
  }
});
</script>

<style scoped>
.chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%; /* 或者指定一个具体的高度 */
}
</style>
